package com.qsl.manager;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.VFS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.URI;

/**
 * 文件上传 manager
 * @author 青石路
 */
@Component
public class FileUploadManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadManager.class);
    // private static final StandardFileSystemManager systemManager;
    private static final FileSystemManager systemManager;

    @Autowired
    @Qualifier("fptUri")
    private URI fptUri;
    @Autowired
    private FileSystemOptions fileSystemOptions;

    static {
        try {
            systemManager = VFS.getManager();
            /*systemManager = new StandardFileSystemManager();
            systemManager.setFilesCache(new NullFilesCache());
            systemManager.init();*/
        } catch (FileSystemException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean uploadFileToSftp(File file, String fileName, boolean isRetry) {
        String destDir = fptUri.toString();
        try {
            FileObject srcObject = systemManager.resolveFile(file.getParentFile(), file.getName());
            FileObject destObjectDir = systemManager.resolveFile(destDir, fileSystemOptions);
            FileObject destObject = systemManager.resolveFile(destObjectDir, fileName);
            destObject.copyFrom(srcObject, Selectors.SELECT_SELF);
            return true;
        } catch (FileSystemException e) {
            if (isRetry) {
                try {
                    LOGGER.info("创建目录{}开始", destDir);
                    FileObject destObjectDir = systemManager.resolveFile(destDir, fileSystemOptions);
                    destObjectDir.createFolder();
                    LOGGER.info("创建目录{}开始", destDir);
                } catch (FileSystemException ex) {
                    LOGGER.error("创建目录失败，异常：", ex);
                }
                return uploadFileToSftp(file, fileName, false);
            }
            LOGGER.error("文件:{} 上传SFTP失败，异常：", file.getAbsoluteFile(), e);
            return false;
        }
    }
}
